// 移动端调试工具
class MobileDebug {
  constructor() {
    this.isDebug = process.env.NODE_ENV === 'development'
    this.logs = []
    this.init()
  }

  init() {
    if (!this.isDebug) return

    // 延迟初始化，等待Vue加载完成
    setTimeout(() => {
      this.catchError()
      this.createDebugPanel()
      this.logDeviceInfo()
    }, 100)
  }

  // 捕获错误
  catchError() {
    // Vue错误处理 - 安全检查
    if (window.Vue && window.Vue.config) {
      const originalErrorHandler = window.Vue.config.errorHandler
      window.Vue.config.errorHandler = (err, vm, info) => {
        this.log('Vue Error:', err.message, 'error')
        if (originalErrorHandler) originalErrorHandler(err, vm, info)
      }
    }

    // 全局错误捕获
    window.addEventListener('error', (event) => {
      const message = event.error ? event.error.message : event.message
      this.log('Global Error:', message, 'error')
    })

    // Promise错误捕获
    window.addEventListener('unhandledrejection', (event) => {
      const reason = event.reason && event.reason.message ? event.reason.message : event.reason
      this.log('Promise Error:', reason, 'error')
    })
  }

  // 记录日志
  log(title, content, type = 'info') {
    const logItem = {
      title,
      content,
      type,
      time: new Date().toLocaleTimeString()
    }

    this.logs.unshift(logItem)

    // 限制日志数量
    if (this.logs.length > 100) {
      this.logs = this.logs.slice(0, 100)
    }

    // 更新调试面板
    this.updateDebugPanel()

    // 控制台输出
    if (console[type]) {
      console[type](title, content)
    } else {
      console.log(title, content)
    }
  }

  // 记录设备信息
  logDeviceInfo() {
    const deviceInfo = {
      userAgent: navigator.userAgent,
      screenWidth: window.screen.width,
      screenHeight: window.screen.height,
      innerWidth: window.innerWidth,
      innerHeight: window.innerHeight,
      devicePixelRatio: window.devicePixelRatio,
      platform: navigator.platform,
      cookieEnabled: navigator.cookieEnabled,
      onLine: navigator.onLine,
      language: navigator.language,
      href: window.location.href
    }

    this.log('Device Info', deviceInfo, 'info')
  }

  // 创建调试面板
  createDebugPanel() {
    // 避免重复创建
    if (document.getElementById('mobile-debug-panel')) return

    const debugPanel = document.createElement('div')
    debugPanel.id = 'mobile-debug-panel'
    debugPanel.style.cssText = `
      position: fixed;
      top: 20px;
      right: 20px;
      width: 50px;
      height: 50px;
      background: #ff6b6b;
      border-radius: 50%;
      color: white;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 12px;
      font-weight: bold;
      z-index: 9999;
      cursor: pointer;
      box-shadow: 0 2px 10px rgba(0,0,0,0.3);
      user-select: none;
      -webkit-user-select: none;
    `
    debugPanel.innerHTML = 'DEBUG'

    debugPanel.onclick = () => this.toggleDebugModal()

    document.body.appendChild(debugPanel)
    this.log('Debug Panel', '调试面板已创建', 'info')
  }

  // 切换调试模态框
  toggleDebugModal() {
    let modal = document.getElementById('mobile-debug-modal')

    if (modal) {
      modal.remove()
      return
    }

    modal = document.createElement('div')
    modal.id = 'mobile-debug-modal'
    modal.style.cssText = `
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background: rgba(0,0,0,0.8);
      z-index: 10000;
      overflow: auto;
    `

    const content = document.createElement('div')
    content.style.cssText = `
      background: white;
      margin: 20px;
      border-radius: 8px;
      max-height: calc(100vh - 40px);
      overflow: auto;
    `

    const header = document.createElement('div')
    header.style.cssText = `
      padding: 15px;
      border-bottom: 1px solid #eee;
      font-weight: bold;
      display: flex;
      justify-content: space-between;
      align-items: center;
      background: #f8f9fa;
    `

    const closeBtn = document.createElement('button')
    closeBtn.innerHTML = '×'
    closeBtn.style.cssText = `
      background: none;
      border: none;
      font-size: 18px;
      cursor: pointer;
      color: #666;
      padding: 0;
      width: 24px;
      height: 24px;
      display: flex;
      align-items: center;
      justify-content: center;
    `
    closeBtn.onclick = () => modal.remove()

    const clearBtn = document.createElement('button')
    clearBtn.innerHTML = '清空'
    clearBtn.style.cssText = `
      background: #007aff;
      color: white;
      border: none;
      padding: 4px 8px;
      border-radius: 4px;
      cursor: pointer;
      font-size: 12px;
      margin-right: 8px;
    `
    clearBtn.onclick = () => {
      this.clearLogs()
      this.updateDebugPanel()
    }

    header.innerHTML = `<span>调试日志 (${this.logs.length})</span>`
    const rightButtons = document.createElement('div')
    rightButtons.appendChild(clearBtn)
    rightButtons.appendChild(closeBtn)
    header.appendChild(rightButtons)

    const logContainer = document.createElement('div')
    logContainer.id = 'debug-log-container'
    logContainer.style.cssText = `
      padding: 15px;
      max-height: 400px;
      overflow: auto;
    `

    content.appendChild(header)
    content.appendChild(logContainer)
    modal.appendChild(content)

    modal.onclick = (e) => {
      if (e.target === modal) modal.remove()
    }

    document.body.appendChild(modal)
    this.updateDebugPanel()
  }

  // 更新调试面板
  updateDebugPanel() {
    const container = document.getElementById('debug-log-container')
    if (!container) return

    if (this.logs.length === 0) {
      container.innerHTML = '<div style="text-align: center; color: #999; padding: 20px;">暂无日志</div>'
      return
    }

    container.innerHTML = this.logs.map(log => `
      <div style="
        margin-bottom: 10px; 
        padding: 8px; 
        border-radius: 4px; 
        background: ${log.type === 'error' ? '#fee' : log.type === 'warn' ? '#fff3cd' : '#f8f9fa'};
        border-left: 3px solid ${log.type === 'error' ? '#dc3545' : log.type === 'warn' ? '#ffc107' : '#007bff'};
        font-size: 12px;
        line-height: 1.4;
      ">
        <div style="font-weight: bold; color: ${log.type === 'error' ? '#dc3545' : log.type === 'warn' ? '#856404' : '#495057'};">
          [${log.time}] ${log.title}
        </div>
        <div style="margin-top: 4px; word-break: break-all; white-space: pre-wrap;">
          ${typeof log.content === 'object' ? JSON.stringify(log.content, null, 2) : log.content}
        </div>
      </div>
    `).join('')
  }

  // 清空日志
  clearLogs() {
    this.logs = []
    this.updateDebugPanel()
    this.log('System', '日志已清空', 'info')
  }
}

// 全局安装 - 延迟到DOM加载完成后
if (typeof window !== 'undefined') {
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', () => {
      window.mobileDebug = new MobileDebug()
    })
  } else {
    window.mobileDebug = new MobileDebug()
  }
}

export default MobileDebug 